package com.speechb.common;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

public class WXUtil {
    /**
     * 获取微信小程序 session_key 和 openid
     */
    public static JSONObject getSessionKeyAndOropenid(String code){
        String param = "appid=wx88d150f4749832c9&secret=e07f2b8c22dc8c311207f3426d753202&js_code="+code;
        String respMsg = HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", param);
        return JSON.parseObject(respMsg);
    }


    public static void main(String args[]) {
        String test= "81NfYispPjd4Ld7Imah+298zUdh+GQrZ4ugyrMjV3tje+xLeP5mNM/DBmFhv8L2DkCYF241jnVzdss519ccWNC3omjDtSz7XjpoRfuqFJ/k1CAiBfc7TH4nzjgZCG5rIdH1Au75UqKkrQNHhDtIwZ74yP6yDTH4TbOlOU8grIz/WXkhVXNU4ipfqqHrXtMzRKFm45r+xXtNouEgq//LOGBMN2csMZKoWC2MZ6U2igswAt6LfJaWuDIzJSXOZdu4AOEkKx4F9DQCRypJlxat7En+y/Ddp6nBGu0qfwsWoHl7Fd5oCOREZG8qETsQ7GJ4Se+u3YqlD9svU4sh1MgVBieSmgdt1IIVHoMmT+uNUmiJLw1ttn1haSzlBgA0ULIV7JM5Dtbk0PAWtORXONX7Q2nAE05AOGXjDkfIMQYcHw9C8XFyg6KpGc+CM/I3qadCZc73pjvD0jOgyJ1nD7z+0jg==";
        System.out.println(getUserInfo("003TwFkl256zC64ZY8nl2Jx5UJ1TwFkB",test,"av8oEePumSFPahi8Kl4kBg=="));
    }

    /**
     * 解密用户敏感数据获取用户信息
     *
     * @param code    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     */
    public static JSONObject getUserInfo(String code,String encryptedData, String iv) {
        JSONObject jsonObject = getSessionKeyAndOropenid(code);
        String sessionKey = jsonObject.getString("session_key");
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);

        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {

                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);

                byte[] temp = new byte[groups * base];

                Arrays.fill(temp, (byte) 0);

                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);

                keyByte = temp;

            }

            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}